package sys.cloud.escape;


import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
/**
 * Created by shiyusen on 2017/3/23.
 */
//@WebFilter(urlPatterns = "/*", filterName = "indexFilter")
public class GuestbookFilter implements Filter {

    private static final String WORD_FILE="word_file";
    HashMap<String,String> map = new HashMap<String,String>();
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
//        String action = request.getParameter("action");
//        if(action==null||action.equals("")){
//            chain.doFilter(request, response);
//            return ;
//        }

        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpRes = (HttpServletResponse) response;

        MyRequestWrapper reqWrapper = new MyRequestWrapper(httpReq);
        MyResponseWrapper resWrapper = new MyResponseWrapper(httpRes);

        //LeavelMessage 和 WebUtils 见下方额外代码
        LeavelMessage message =new LeavelMessage();
        WebUtils.requestParam2Bean(reqWrapper,message);
        message.setDate(new Date());
        reqWrapper.getSession().setAttribute("leavelMassage",message);

        chain.doFilter(reqWrapper, resWrapper);

        String content =new String(resWrapper.toByteArray());
        String result = replaceText(content);
        httpRes.setContentType("text/html;charset=utf-8");
        PrintWriter out = httpRes.getWriter();
        out.println(result);

    }

    private String replaceText(String content) {
        if(content==null)return null;
        StringBuffer sb = new StringBuffer(content);
        Set<String> keys = map.keySet();
        Iterator it  = keys.iterator();
        while(it.hasNext()){
            String key = (String)it.next();
            int index = content.indexOf(key);
            if(index!=-1){
                sb.replace(index, index+key.length(), map.get(key));
            }
        }
        return sb.toString();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String configPath = filterConfig.getInitParameter(WORD_FILE);
        ServletContext sc = filterConfig.getServletContext();
        String filePath = sc.getRealPath(configPath);

        try {
            FileReader fr = new FileReader(filePath);
            BufferedReader bfr = new BufferedReader(fr);

            String line;
            while((line=bfr.readLine())!=null){
                String[] strTemp = line.split("=");
                map.put(strTemp[0], strTemp[1]);
            }
        } catch (Exception e) {
            System.out.println("读取过滤文件信息出错!");
        }
    }

}
